package com.xinxin.socket.handler;

import com.xinxin.socket.constant.CommandId;
import com.xinxin.socket.context.ChannelContext;
import com.xinxin.socket.msg.NetMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class NetMsgHandler extends ChannelInboundHandlerAdapter {

    private final ChannelContext channelContext = ChannelContext.getInstance();

    @Override
    public final void channelRead(ChannelHandlerContext ctx, Object msg) {
        /*
        ProxySession proxySession = ProxySession.Manager.get(ctx);
        if (proxySession == null) {
            // TODO deal session
        }
        */

        NetMsg netMsg = (NetMsg) msg;

        if (netMsg.getCmdId() == CommandId.SYS_HEART_PING) {
            channelContext.receiveHeart(ctx);

            netMsg.setCmdId(CommandId.SYS_HEART_REPLY);
            ctx.writeAndFlush(netMsg);
        }

        try {
            // netMsg.retain();
            channelRead0(ctx, netMsg);
        } catch (Exception e) {
            log.error("handler error {}", getClass().getSimpleName(), e);
        } finally {
            // netMsg.release();
        }

        ctx.fireChannelRead(msg);
    }

    protected abstract void channelRead0(ChannelHandlerContext ctx, NetMsg netMsg) throws Exception;
}
